package core

import (
	"fmt"
	"sync"
)

type PlayerMgr struct {
	PlayerList map[int32]*Player
	pLock      sync.RWMutex //保护Playey的互斥锁
}

var PlayerMgrObj *PlayerMgr

func init() {
	PlayerMgrObj = &PlayerMgr{
		PlayerList: make(map[int32]*Player),
	}
}

func (pm *PlayerMgr) AddPlayer(player *Player) {
	pm.pLock.Lock()
	pm.PlayerList[player.PID] = player
	pm.pLock.Unlock()

	WorldMgrObj.AddPlayer(player)

	fmt.Println("Current PlayerCount:", len(pm.PlayerList))
}

func (pm *PlayerMgr) RemovePlayer(PID int32) {
	if pm.PlayerList[PID] != nil {
		pm.pLock.Lock()
		delete(pm.PlayerList, PID)
		pm.pLock.Unlock()
	}
}

func (pm *PlayerMgr) GetPlayerByPID(PID int32) *Player {
	pm.pLock.RLock()
	defer pm.pLock.RUnlock()
	return pm.PlayerList[PID]
}

func (pm *PlayerMgr) GetAllPlayers() []*Player {
	pm.pLock.RLock()
	defer pm.pLock.RUnlock()

	players := make([]*Player, 0)

	for _, v := range pm.PlayerList {
		players = append(players, v)
	}

	return players
}
